package com.zhaolang.qogir.domain.impl;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.BaseResp;
import com.zhaolang.qogir.domain.Register;
import com.zhaolang.qogir.server.ClientCallbackImpl;
import com.zhaolang.qogir.server.RadarProxy;
import com.zhaolang.qogir.server.ServerRequestParams;
import com.zhaolang.qogir.util.GsonUtil;
import com.zhaolang.qogir.util.HttpConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RegisterImpl extends Register {
    private Context context;
    private Handler handler1;
    private Handler handler2;
    private ServerRequestParams params;

    public RegisterImpl(Context context) {
        this.context = context;
    }

    @Override
    public void regAsync(RegReq bean, final BaseCall<BaseResp> call) {

        handler1 = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (call != null && !call.cancel) {
                    call.call((BaseResp) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(writeRegParams(bean), new ClientCallbackImpl() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject;
                BaseResp resp = new BaseResp();
                Log.d("Radar", "Radar. regAsync: " + result);
                try {
                    jsonObject = new JSONObject(result);
                    resp.setSuccess(jsonObject.optBoolean("success"));
                    resp.setStatusCode(jsonObject.optInt("statusCode"));
                    JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                    resp.setMessage(jsonObject2.optString("msg"));
                    resp.setStatus(jsonObject2.optString("status"));
                    //resp.setErrCode(jsonObject2.optString("err"));
                    resp.setErrCode(jsonObject.optString("statusCode"));

                    JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("values"));
                    String token = jsonObject3.optString("token");
                    if ((token != null) && (!token.equals(""))) {
                        writeLocalContent(token);
                    }

                    String userId = jsonObject2.optString("userId");
                    String userMsNum = jsonObject2.optString("msNum");
                    if (!TextUtils.isEmpty(userId)) {
                        SharePreCacheHelper.setUserID(context, userId);
                    }
                    if (!TextUtils.isEmpty(userMsNum)){
                        SharePreCacheHelper.setUserMsNum(context, userMsNum);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.setStatus("FAILED");
                    Log.d("Radar", "JSONException: " + e);
                }
                Message msg = Message.obtain();
                msg.obj = resp;
                handler1.sendMessage(msg);
            }

            @Override
            public void onFailure(String result) {
                BaseResp resp = new BaseResp();
                resp.setStatus("FAILED");
                Message msg = Message.obtain();
                msg.obj = resp;
                handler1.sendMessage(msg);
                System.out.println(result);
            }
        });
    }

    private void writeLocalContent(String token) {
        HttpConstant.TOKEN = token;
        //RadarProxy.getInstance(context).startLocalData(HttpConstant.getLoginUrl(null), token, null);
        SharePreCacheHelper.setUserToken(context, token);
    }

    @Override
    public void regRadarAsync(RegRadarReq bean, final BaseCall<RegRadarResp> call) {

        handler2 = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (call != null && !call.cancel) {
                    call.call((RegRadarResp) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(writeRadarRegParam(bean), new ClientCallbackImpl() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject;
                RegRadarResp resp = new RegRadarResp();
                Log.d("Radar", "regRadarAsync: " + result);
                try {
                    jsonObject = new JSONObject(result);
                    resp.setSuccess(jsonObject.optBoolean("success"));
                    resp.setStatusCode(jsonObject.optInt("statusCode"));
                    JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                    resp.setMessage(jsonObject2.optString("msg"));
                    resp.setStatus(jsonObject2.optString("status"));
                    JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("values"));
                    resp.setUserId(jsonObject3.optString("uid"));
                    String UserId = jsonObject3.optString("uid");
                    String EMUserId = jsonObject3.optString("msgUid");
                    if (!TextUtils.isEmpty(UserId)) {
                        SharePreCacheHelper.setUserID(context, UserId);
                    }
                    if (!TextUtils.isEmpty(EMUserId)) {
                        SharePreCacheHelper.setEMUserId(context, EMUserId);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.setStatus("FAILED");
                    Log.d("Radar", "JSONException: " + e);
                }
                Message msg = Message.obtain();
                msg.obj = resp;
                handler2.sendMessage(msg);
            }

            @Override
            public void onFailure(String result) {
                RegRadarResp resp = new RegRadarResp();
                resp.setStatus("FAILED");
                Message msg = Message.obtain();
                msg.obj = resp;
                handler2.sendMessage(msg);
                System.out.println(result);
            }
        });
    }

    private ServerRequestParams writeRegParams(RegReq bean) {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.getRegUrl(null));
        Map<String, Object> requestParam = new HashMap<String, Object>();
        requestParam.put("USERNAME", bean.getUserId());
        requestParam.put("PASSWORD", bean.getPwd());
        requestParam.put("rcode", bean.getVerifyCode());
        requestParam.put("regionCode", bean.getRegionCode());
        requestParam.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(requestParam);
        return params;
    }

    private ServerRequestParams writeRadarRegParam(RegRadarReq bean) {
        params = getServerRequest();
        params.setToken(HttpConstant.TOKEN);
        params.setRequestParam(null);
        params.setRequestEntity(GsonUtil.getGson().toJson(bean));
        return params;
    }

    private ServerRequestParams getServerRequest() {
        if (params == null) {
            params = new ServerRequestParams();
        }
        return params;
    }

}
